package com.chap1.waitandnotify;

import com.chap1.tools.SleepTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-03-28
 * Time: 5:39
 * To change this template use File | Settings | File Templates.
 */
public class DBPoolTest {
    static DBPool dbPool = new DBPool(2);
    static CountDownLatch end;

    public static void main(String[] args) throws InterruptedException {
        int threadCount = 5;
        end = new CountDownLatch(threadCount);
        int count = 2;
        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();

        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(new Worker(count,got,notGot),"worker_"+i);
            thread.start();
        }
        end.await();
        System.out.println("总共尝试了: " + (threadCount * count));
        System.out.println("拿到连接的次数：  " + got);
        System.out.println("没能连接的次数： " + notGot);
    }

    static class Worker implements Runnable{
        int count;
        AtomicInteger got;
        AtomicInteger notGot;

        public Worker(int count, AtomicInteger got, AtomicInteger notGot) {
            this.count = count;
            this.got = got;
            this.notGot = notGot;
        }

        @Override
        public void run() {
            while (count>0){
                try{
                    Connection connection = dbPool.fetchConnection(1);
                    if (connection!=null){
                        try {
                            PreparedStatement preparedStatement = connection.prepareStatement("");
                            preparedStatement.execute();
                            connection.commit();
                        }finally {
                            dbPool.releaseConnection(connection);
                            got.incrementAndGet();
                        }
                        SleepTools.ms(2);
                        dbPool.releaseConnection(connection);
                        got.incrementAndGet();

                    }else {
                        notGot.incrementAndGet();
                        System.out.println(Thread.currentThread().getName()
                                +"等待超时!");
                    }
                }catch (Exception e){
                }finally {
                    count--;
                }
            }
            end.countDown();
        }
    }
}
